const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (error) {
            this.reject(error)
        }
    }
    // 成功fulfilled 失败rejected 等待pending
    // 状态只能由等待转为成功或失败，转后不更改
    status = PENDING;
    //成功的指和失败的回调
    value = undefined;
    error = undefined;
    //成功回调和失败回调
    //为了异步操作时than调用多个处理函数，使用数组存储起来
    successCallback = [];
    failCallback = [];

    resolve = value => {
        //判断状态是否是等待
        if (this.status !== PENDING) return;
        this.status = FULFILLED;
        this.value = value;
        // this.successCallback && this.successCallback(this.value);
        while (this.successCallback.length) this.successCallback.shift()();
    }

    reject = error => {
        //判断状态是否是等待
        if (this.status !== PENDING) return;
        this.status = REJECTED;
        this.error = error;
        this.failCallback && this.failCallback(this.error);
        while (this.failCallback.length) this.successCallback.shift()();
    }

    then(successCallback, failCallback) {
        // 参数可选
        successCallback = successCallback ? successCallback : value => value;
        failCallback = failCallback ? failCallback : reason => { throw reason };
        let promise2 = new Promise((resolve, reject) => {
            //判断状态，执行成功或是失败回调
            if (this.status === FULFILLED) {
                //直接调用promise2是调用不了的 因为这时在创建pomise2中 所以要异步调用
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                        //返回值可能时普通值和promise对象
                        //普通值直接调用resolve,promise对象根据状态调用resolve或者reject
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (error) {
                        reject(error)
                    }

                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.error)
                        resolvePromise(promsie2, x, resolve, reject)
                    } catch (error) {
                        reject(error);
                    }
                }, 0)
            } else {
                //非立即执行时，保持等待状态
                //等待，存储成功回调和失败回调
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value);
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason);
                            resolvePromise(promsie2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
            }
        });
        //返回promise对象以实现than的链式调用
        return promise2
    }
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    static all(array) {
        let result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i];
                if (current instanceof MyPromise) {
                    // promise 对象
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    // 普通值
                    addData(i, array[i]);
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value));
    }
}



function resolvePromise(promise2, x, resolve, reject) {
    //防止自己返回自己进入死循环
    if (promise2 === x) {
        return reject(new TypeError(''))
    }
    if (x instanceof MyPromise) {
        //promise对象
        // x.then(value => resolve(value),error=>reject((error)))
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}

module.exports = MyPromise;